package service

import (
	"fmt"
	"mime/multipart"
	"path/filepath"
	"time"

	"douyin/models"
	"douyin/repository/mysql"
	"douyin/setup/settings"
	"douyin/utils/pkg/oss"

	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
)

// Publish 视频投稿
func Publish(data *multipart.FileHeader, userId int64, title string) (err error) {
	eg := new(errgroup.Group) //创建等待组
	channel := make(chan string)
	// 1.文件全路径
	filename := filepath.Base(data.Filename)
	timeStamp := time.Now().UnixNano()
	finalName := fmt.Sprintf("%d_%d_%s", timeStamp, userId, filename)
	saveFilePath := filepath.Join(settings.Conf.OssConfig.Path, finalName)

	fmt.Printf("SaveFilePath :%v\n", saveFilePath)

	// 2.上传到oss,获取PlayUrl
	eg.Go(func() error {
		playUrl, err := oss.UploadAliyunOss(data, saveFilePath)
		channel <- playUrl
		if err != nil {
			return err
		}
		return nil
	})
	playUrl := <-channel
	if err = eg.Wait(); err != nil {
		zap.L().Error("oss.UploadAliyunOss failed", zap.Error(err))
		return
	}
	//3.获取视频封面(默认x-oss-process=video/snapshot,t_1000,m_fast)
	coverUrl := playUrl + "?x-oss-process=video/snapshot,t_1000,m_fast"
	//4.插入数据库Vid记录
	vid := &models.Vid{
		Id:            0,
		PlayUrl:       playUrl,
		CoverUrl:      coverUrl,
		FavoriteCount: 0,
		CommentCount:  0,
		Title:         title,
		IsFavorite:    false,
	}
	err = mysql.InsertVid(vid)
	if err != nil {
		zap.L().Error("mysql.InsertVid failed", zap.Error(err))
		return
	}
	//5.插入数据库Publisher记录
	pub := &models.Publisher{
		UserId:  userId,
		VideoId: vid.Id,
	}
	err = mysql.InsertPublisher(pub)
	if err != nil {
		zap.L().Error("mysql.InsertPublisher failed", zap.Error(err))
		return
	}
	return
}

// PublishList 发布视频列表
func PublishList(userId, otherId int64) (videoList []models.Video, err error) {
	//1.根据otherId, 查找Publishers表,得到用户发布的所有视频Id
	vidIds, err := mysql.SelectPublisher(otherId)
	if err != nil {
		zap.L().Error("mysql.SelectPublisher failed", zap.Error(err))
		return
	}
	//2.根据Ids,查找视频，返回Video切片
	videoList, err = mysql.SelectVideos(vidIds, userId)
	if err != nil {
		zap.L().Error("mysql.SelectVid failed", zap.Error(err))
		return
	}
	return
}
